#include "logwidget.h"

LogWidget::LogWidget(QWidget *parent) : QWidget(parent)
{
    this->initUI();
    this->resize(600,800);
}

void LogWidget::initUI()
{

    this->con=MyControl::getInstance();
    this->title=new QLabel("操作日志界面");
    this->tableWidget=new QTableWidget();
    this->ret_button=new QPushButton("返回");


    this->layout_H1=new QHBoxLayout();
    this->layout_H2=new QHBoxLayout();
    this->layout_H3=new QHBoxLayout();
    this->layout_V=new QVBoxLayout();

    this->layout_H1->addWidget(title);
    this->layout_H2->addWidget(tableWidget);
    this->layout_H3->addWidget(ret_button);

    this->layout_V->addLayout(layout_H1);
    this->layout_V->addLayout(layout_H2);
    this->layout_V->addLayout(layout_H3);


    layout_H1->addWidget(title);
    layout_H1->setAlignment(Qt::AlignCenter);

    this->setLayout(this->layout_V);




    this->model=this->con->getModel("logAddUser");
    QString sql=QString("select operation_log.operation_time,operation_log.log_device,user_info.username, operation_log.operation_type from operation_log JOIN  user_info ON user_info.user_id=%1 ORDER BY operation_log.log_id DESC LIMIT 10;")
            .arg(id);
    Any ret=this->model->sqlSelect((char *)sql.toStdString().c_str());
    this->vec=ret.cast_<QList<LogAddUser*>>();


    QStringList dataList;
    QList<LogAddUser*>::iterator iter=vec.begin();
    while(vec.end()!=iter)
    {
        dataList.append((*iter)->getTime());
        dataList.append((*iter)->getLog_device());
        dataList.append((*iter)->getUsername());
        dataList.append((*iter)->getType());

        iter++;
    }

    tableWidget->setColumnCount(4); // 4列：时间、设备编号、警员编号、操作类型
    tableWidget->setHorizontalHeaderLabels({"时间", "设备编号", "警员编号", "操作类型"});
    int rowCount = vec.size();
    tableWidget->setRowCount(rowCount);

    for (int row = 0; row < rowCount; ++row) {
            for (int col = 0; col < 4; ++col) {
                int index = row * 4 + col;
                if (index < dataList.size()) {
                    QTableWidgetItem* item = new QTableWidgetItem(dataList[index]);
                    tableWidget->setItem(row, col, item);
                } else {
                    // 处理索引越界情况
                    qDebug() << "Index out of range: " << index;
                    break;
                }
            }
    }



    connect(this->ret_button,&QPushButton::clicked,this,&LogWidget::ret);
}

void LogWidget::ret()
{
    emit RetToMain();
}
